package com.foton.bpc.all.config.plaugins;
import com.foton.bpc.all.config.ProtocolConfig;
import com.foton.bpc.all.config.RegisterConfig;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.type.AnnotationMetadata;

import java.lang.reflect.Field;

/**
 * @Author RenPu
 * @Date 2023/6/5 17:19
 * @Version 1.0
 * @Description: 读取配置文件，封装到BeanDefinition对象，装载到spring容器
 **/
public class ConrfigBeanRegister implements ImportBeanDefinitionRegistrar {

    StandardEnvironment environment;

    public ConrfigBeanRegister(Environment environment) {
        this.environment = (StandardEnvironment)environment;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //构建BeanDefinitionBuilder对象
        BeanDefinitionBuilder builder=null;
        builder= BeanDefinitionBuilder.genericBeanDefinition(ProtocolConfig.class);
        //从env环境对象里获取配置文件得值
       for(Field field: ProtocolConfig.class.getDeclaredFields()){
           String value = environment.getProperty("trpc.protocol."+field.getName());
           builder.addPropertyValue(field.getName(),value);

       }

        //封装到BeanDefinition装载到容器中
        registry.registerBeanDefinition("protocolConfig",builder.getBeanDefinition());



        //构建BeanDefinitionBuilder对象
        builder= BeanDefinitionBuilder.genericBeanDefinition(RegisterConfig.class);
        //从env环境对象里获取配置文件得值
        for(Field field: RegisterConfig.class.getDeclaredFields()){
            String value = environment.getProperty("trpc.registry."+field.getName());
            builder.addPropertyValue(field.getName(),value);

        }

        //封装到BeanDefinition装载到容器中
        registry.registerBeanDefinition("registerConfig",builder.getBeanDefinition());



    }
}
